home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
PC World Interactive 7
/
PC World Interactive 7.iso
/
program
/
ctutord.EXE
/
POINTERS.C
< prev
next >
Wrap
C/C++ Source or Header
|
1990-10-25
|
3KB
|
69 lines
/*
Remember the rules of precedence. For the operators ++, --, and the
pointer reference for indirection *, precedence is from right to left.
When one of those operators is detected by the compiler, the compiler
will determine whether indirection is required. The following cases
using a pointer to an integer help to illustrate this point:
Given the following definitions:
int *p, i;
i=99; p=&i;
The compiler determines the operation to be performed:
*p Access the contents of i via the pointer p
++p Increment p to point to the next integer
p Access the address stored in p
++*p Increment the contents of i via the pointer p before referencing
*++p Increment p to point to the next integer, then reference the
integer.
*p++ Increment p to point to the next integer, after the current
integer pointed to by p is referenced.
p++* ILLEGAL unless * is used to multiply the pointer value
p*++ ILLEGAL
*/
main()
{
int i, j, k, *p;
static int array[]= { 1,2,3 };
j=999; k=1234; i=9; p=&i;
printf("%d\n",i++); /* prints: 9 */
printf("%d\n",*p); /* prints: 10 */
printf("%d\n",++*p); /* prints: 11 */
printf("%d\n",*++p); /* prints: 999, First, p gets incremented to point
to the next integer. This just happens to be j since j
is defined after i. Then the contents of integer
j would be passed to printf(). This is the makings
of a major bug. This is shown only to illustrate
how a pointer could be misused without the compiler
catching the problem. */
printf("%d\n",*p++); /* prints: 999, p gets incremented after it passes
999 */
/* it just so happens that the next integer would be k, since k is defined
after j. This would normally create a bug for the programmer that could be
difficult to find. */
printf("%d\n",*p); /* prints: 1234, Since p was incremented on the
previous line, the pointer was incremented to point
to the next integer. This just happens to be the
integer k - watch out for bugs like these! */
/* ERROR printf("%d\n",p++*); */
/* ERROR printf("%d\n",p*++); */
/* A better utilization of pointer arithmetic could be implemented when
the contents of an array are accessed.
*/
p=&array[0];
printf("%d\n",*p); /* prints: 1 */
printf("%d\n",++*p); /* prints: 2 */
printf("%d\n",*++p); /* prints: 2 */
printf("%d\n",*p++); /* prints: 2 */
printf("%d\n",*p); /* prints: 3 */
}